package com.slorgs.web.controller

import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.slorgs.business.service.UserService
import com.slorgs.business.utils.ThreadLocalUtil
import com.slorgs.business.utils.ValidateCodeUtils
import com.slorgs.infrastructure.dto.ResponseDTO
import com.slorgs.infrastructure.dto.UserDTO
import com.slorgs.infrastructure.model.User
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.web.bind.annotation.*
import java.io.IOException
import javax.annotation.Resource

@RestController
@RequestMapping("/user")
@CrossOrigin
class UserController {

    @Resource
    var stringRedisTemplate: StringRedisTemplate? = null

    @Resource
    var userService: UserService? = null

    @Resource
    var validateCodeUtils: ValidateCodeUtils? = null

    @PostMapping("/register")
    fun register(@RequestBody user: User?): ResponseDTO? {
        return userService?.register(user)
    }

    @PostMapping("/login")
    fun login(@RequestBody user: UserDTO?): ResponseDTO? {
        return userService?.login(user)
    }

    @PostMapping("/toLogin")
    fun toLogin(@RequestBody userDTO: UserDTO?, isPassword: Boolean): ResponseDTO? {
        return userService?.portalLogin(userDTO, isPassword)
    }

    @PostMapping("/portalLogin")
    fun portalLogin(@RequestBody userDTO: UserDTO?): ResponseDTO? {
        return userService?.portalLogin(userDTO, true)
    }

    @GetMapping("/getCurrentUser")
    fun getCurrentUser(): String? {
        return ThreadLocalUtil.getUser()?.realName
    }

    @PostMapping("/list")
    fun list(@RequestBody user: User?, page: Page<*>?): ResponseDTO? {
        return userService?.userList(user, page)
    }

    @GetMapping("/getValidateCode")
    @CrossOrigin
    @Throws(IOException::class)
    fun getVerify(browserIdentity: String?): ResponseDTO? {
        return stringRedisTemplate?.let { browserIdentity?.let { it1 -> validateCodeUtils?.getRandomCode(it, it1) } }
    }

    @GetMapping("/getMailValidateCode")
    fun getMailValidateCode(mail: String?): ResponseDTO? {
        return stringRedisTemplate?.let { mail?.let { it1 -> validateCodeUtils?.getMailCode(it1, it) } }
    }

    @GetMapping("/authorize")
    fun serverAuthorize(onlyMark: String?): ResponseDTO? {
        return userService?.serverAuthorize(onlyMark)
    }

    @GetMapping("/commit/auth")
    fun commitAuth(onlyMark: String?): String? {
        return userService?.commitAuth(onlyMark)
    }

    @GetMapping("/check/auth")
    fun checkAuth(onlyMark: String?): ResponseDTO? {
        return userService?.checkAuth(onlyMark)
    }
}